var aa = ajaxStart();
var timer = null;

function shopcar_edit() {
    var f = $('updateform');
    if(f.emptycar.value == 1 &&!confirm('您确认不需要这些物品了吗？')) {
        f.emptycar.value = 0;
        return false;
    }
    try {
        aa.call('/shopcar.php', 'ajaxShopcarUpdate', shopcaredit_result, f.serialize());
        f.disable();
        return false;
    }
    catch(e) {
        return true;
    }
}

function shopcaredit_result(result) {
    var i;
    var d = $('updatemsg');
    var f = $('updateform');
    var id;
    var t = 'success';
    
    try {
        var stat = result.result[0].data;
        if(stat == 1 || stat == 8) {
            i = '购物车已更新! ';
            if(stat == 8) {
                i += '某些物品数量超过库存，我们自动为您调整了数量。<a href="/faq/24" target="_faq">详情</span>';
                t = 'notice';
            }
            if(result.price == 'undefined' || result.price == null) return _emptycar();
            var dib = new Array();
            for(var j = 0; j < result.price.length; j++) {
                id = result.price[j].id[0].data;
                if(Prototype.Browser.IE)
                    $('price' + id).innerText = result.price[j].price[0].data;
                else
                    $('price' + id).textContent = result.price[j].price[0].data;
                $('amount' + id).value = result.price[j].amount[0].data;
                if(result.price[j].amount[0].data == 0) dib.push(id);
            }
            
            $('totalprice').update(result.total[0].data);
            $('cartotalprice').update(result.total[0].data);
		    $('caramount_em').update(result.totalamount[0].data);
            $('caramount').update(result.totalamount[0].data);
            $('totalamount').update(result.totalamount[0].data);

            if(result.totalamount[0].data == 'undefined' || result.totalamount[0].data == null || result.totalamount[0].data == '') return _emptycar();
        }
        if(stat == 2) {
            i = '<b>更新失败</b>，请检查您的输入后再提交';
            t = 'error';
        }
    }
    catch(e) {
        if(f.emptycar.value == 1) {
            return _emptycar();
            location.reload();
            f.hide();
            i = '加载中';
            var emptycar = 1;
        }
        else {
            i = '服务器错误，请稍候再试';
            t = 'error';
        }
    }
    if(emptycar == 1) {
        location.href = "/shopcar/checkout";
    }
    else {
        try {
            f.enable();
            dib.each(function(id) {
                $('amount'+id).up(1).hide();
            });
            d.show();
            if(i) d.update('<div class="'+ t +'">' + i + '</div>');
            location.href = "#top";
            if(timer) window.clearTimeout(timer);
            timer = setTimeout("$('updatemsg').hide();", 20000);
        }
        catch(e) {
        }
    }
}

function _emptycar() {
	try {
		$('cartext').update('<span id="cartext">您的购物车还是空的<br />继续加油哦！</span>');
		$('icon_shopcar').removeClassName('icon_shopcar_full');
		$('icon_shopcar').addClassName('icon_shopcar_empty');
		$('shopcar_gc').removeClassName('sprites icon_bubble1');
		$('caramount_em').update();
		$('shopcar_c').update('<div class="error">您的购物车中没有任何物品，为何不看看我们的 <a href="/whathot">热门物品</a>?</div>');
		$('shopcarlist_msg').hide();
	}
	catch(e) {}
}

function checkout_submit() {
    var f = $('checkoutform');
    try {
        aa.call('/checkout.php', 'ajaxCheckout', checkout_result, $('checkoutform').serialize());
	    $('checkoutform').disable();
        return false;
    }
    catch(e) {
        return true;
    }
}

function checkout_result(result) {
    var i;
    var d = $('updatemsg');
    var t = 'success';

    try {
        var stat = result.result[0].data;
        if(stat != 1 && stat != 2 && stat != 4 && stat != 8) {
            location.reload();
            return false;
        }
        if(stat == 1) {
            i = '订单已提交成功，请稍候';
            location.href = '/pay.php/' + result.indentid[0].data + '/1';
            return false;
        }
        if(stat == 2)i = '<b>更新失败</b>，请检查您的输入后再提交';
        if(stat == 4) {
            i = '为保证物品能及时快捷的到达您的收中，请填写完整您的收货信息，谢谢!';
            t = 'error';
        }
        if(stat == 8) {
            alert('注意：由于某些物品库存不够，我们调整了您的订单。请再次确认！');
            location.reload();
        }
    }
    catch(e) {
        i = '服务器错误，请稍候再试';
        t = 'error';
    }
    $('checkoutform').enable();
    if(i) {
        d.update('<div class="'+ t +'">' + i + '</div>');
        $('updatemsg_div').show();
        location.href = "#top";
        if(timer) window.clearTimeout(timer);
        timer = setTimeout("$('updatemsg_div').hide();", 20000);
    }
}

function change_voucher() {
    try {
        $('voucher_btn_sub').disabled = true;
        aa.call('/voucher.php', 'ajaxGetVoucher', change_voucher_result, 'str=' + $F('voucher_code') + '&price=' + totalprice);
    }
    catch(e) {
        alert('服务器错误，请稍候再试');
    }
    return false;
}

function change_voucher_result(result) {
    $('voucher_btn_sub').disabled = false;
    var voucher_price = parseFloat(result.price[0].data);
    var error = parseInt(result.error[0].data);
    var errmsg = '代码无效&nbsp;&nbsp;';
    if(error > 1) {
        if(error == 4) errmsg = '您的购物金额至少要为 &yen;' + voucher_price;
        voucher_price = 0;
        $('voucher_btn', 'voucher_area').invoke('toggle');
    }
    $('voucher_price').update(voucher_price ? '&yen; - ' + voucher_price + '&nbsp;&nbsp;':errmsg);
    if(voucher_price) $('totalprice').update(Math.round((totalprice-voucher_price)*100)/100);
    $('voucher_code_h').value = $F('voucher_code');
    change_sumprice();
}

function change_sumprice(postprice) {
    if(!postprice) {
        var radioGrp = $('checkoutform').postfee;
        for(var i = 0; i < radioGrp.length; i++) {
            if(radioGrp[i].checked) var postprice = parseInt(radioGrp[i].value);
        }
    }
    var sumprice = Math.round((parseFloat($('totalprice').innerHTML)+postprice)*100)/100;
    $('sumprice').update((parseInt(sumprice) > 0 ? sumprice : 0));
}

function animatePoof(imageToPoof) {
    poofCount++;
    if(poofCount >= 6) {
        document.images[imageToPoof].src = "/images/blank.gif";
        clearInterval(poofTimer);
    } else {
        document.images[imageToPoof].src = eval("poof" + poofCount + ".src");
    }
}

function alertme(id) {
    window.open('/alertme.php/' + id + '/pop/', '_alertme', 'width=300,height=200');
    return true;
}

function addtocar(id, msg) {
    if(msg == null) {
        msg = true;
        showmsg = msg;
    }
    aa.call('/addtocar.php', 'ajaxAddToCar', addtocar_result, 'id=' + id);
    return false;
}

function addtocar_result(result) {
    var i;
    var d = $('updatemsg');
    var t = 'success';

    try {
        var stat = result.result[0].data;
        var c = result.count[0].data;
        var p = result.totalprice[0].data;

        if(stat == 1)i = '成功了！您目前共有 <b>' + c + '</b> 件战利品。点击右上角的按钮可以快速结帐';
        if(stat == 2)i = '失败了，没有找到您要加入的物品';
        if(stat == 8)i = '乐铺提醒您：您购物车中的数量已超过该物品库存，您不能够购买更多。<a title="通过我们的帮助系统了解详情" href="/faq.php/23" target="_blank" class="white">详情<\/a>';
        if(stat == 4)i = '很抱歉，我们的网站有些问题，您可以稍候再试一次';
        if(stat == 2 || stat == 4 || stat == 8) {
            t = 'error';
        } else {
            //动画效果
            /*
            poofCount = 0;
            poofTimer = setInterval("animatePoof('car_eff')", 75);

            $('promo').show();
            */
        }
    }
    catch(e) {
        i = '很抱歉，我们的网站有些问题，您可以稍候再试一次';
        t = 'error';
    }
    if(stat == 1) {
		$('cartext').update('<a href="/shopcar">您共有 <b id="caramount">' + c + '<\/b> 件战利品!<br />总价 <b id="cartotalprice">&yen;'+ p +'</b> 元</b></a>');
		$('caramount_em').update(c);
		$('icon_shopcar').addClassName('icon_shopcar_full');
		$('shopcar_gc').addClassName('sprites icon_bubble1');
    }
    if(showmsg == true || stat == 8) {
        try {
            d.update('<div class="'+ t +'">' + i + '</div>');
        }
        catch(e) {
            d.update('<div class="'+ t +'">' + i.replace(/<a.+$/,'') + '</div>');
        }
        d.show();
    } else {
        setCookie("tips_drop", 1, expires_date, "/");
        d.hide();
    }

    if(timer) window.clearTimeout(timer);
    timer = window.setTimeout("$('updatemsg').hide()", 20000);
}

function _dg(m, ele) {
    if (typeof ele == 'undefined') ele = $('itemlist_table') || $('itemlist');
    $A(ele.getElementsByTagName('a')).each(function(node) {
        node.onclick = function(){return m;}
    });
}

function __de(ele) {
    window.setTimeout(function(){_dg(true,ele.element)}, 1000);
}

function __dg(ele) {
    return _dg(false, ele.element);
}

function addtoWishlist(remove,id) {
    try {
        if (remove)
            aa.call('/wishlist.php/add/'+id, 'ajaxnewWishList', addtoWishlist_result, 'remove=1&iid='+id);
        else
            aa.call('/wishlist.php/add/'+id, 'ajaxnewWishList', addtoWishlist_result, 'iid='+id);
        return false;
    } catch (e) {
        return true;;
    }
}

function addtoWishlist_result(result) {
    var i;
    var err = 0;
    var d = $('updatemsg');
    var t = 'error';

    try {
        var stat = result.result[0].data;
        switch(stat) {
            case 1:
            case 4:
                t = 'success';
                i = '该物品已加入您的 Wishlist，您可以在会员中心进行管理';
                $('addtowishlist').update('<a style="font-weight:bold" onclick="javascript:return addtoWishlist(1,'+ id +');" href="/wishlist/add/'+ id +'?remove=1">从我的 Wishlist 中移除</a>');
                break;
            case 8:
                t = 'notice';
                i = '该物品已从您的 Wishlist 中移除';
                $('addtowishlist').update('<a onclick="javascript:return addtoWishlist(0,'+ id +');" href="/wishlist/add/'+ id +'">加入我的 Wishlist</a>');
                break;
            default:
                err = 1;i = '未知错误('+stat+')，请稍候再试';
        }
    } catch(e) {
        i = '服务器错误，请稍候再试';
        err = 1;
    }

    if (i) {
        d.update('<div class="'+ t +'">' + i + '</div>');
        d.show();
        if (timer) window.clearTimeout(timer);
        timer = setTimeout( "$('updatemsg').hide();", 10000);
    }
}

function newComment(id) {
    var f = $('newcommentform');
    $('submit').disabled = true;

    try {
        aa.call('/comments.php/'+ id +'/new', 'ajaxNewComment', newComment_result, 'iid='+ id +'&'+$('newcommentform').serialize());
        return false;
    } catch (e) {
        return true;
    }
}

function newComment_result(result) {
    var i;
    var err = 0;
    var ok = 0;
    var d = $('updatemsg2');

    try {
        var stat = result.result[0].data;
        switch(stat) {
            //case 32:    i = 'Email貌似不正确哦';err = 1;$('umail').focus();break;
            case 16:    i = '姓名不能为空哟';err = 1;$('uname').focus();break;
            case 8:     i = '老兄，你想说什么呀';err = 1;$('body').focus();break;
            case 128:   i = '不要这么小气啊，再说点吧';err = 1;$('body').focus();break;
            case 4:     i = '相同的话说一遍就行了喔';err = 1;$('body').focus();break;
            case 1:
                    var node = result.cdata[0];
                    var newhtml = '<div style="background:#ebe8dd;padding:4px;margin:10px;border:1px solid #EEEEEE">';
                    newhtml += '<img alt="" width="32" height="32" src="/images/icon/no-gravatar.gif" align="left" hspace="5" />';
                    newhtml += '<b class="default">'+ node.uname[0].data +'</b>@'+ node.updated[0].data +'<br />';
                    newhtml += '<blockquote style="margin:0.6em">' + node.body[0].data + '</blockquote></div>';
                    $('items_comments_list').insert({top:newhtml});
                    ok = 1;$('rand_code_img').src = '/rand_code.php?'+Math.random();
                    new Effect.ScrollTo('items_comments_list');
                    $('newcommentform').reset();
                    break;
            case 256:
                    i = '您输入的验证数字不正确,或者您的留言中不包括中文，请检查';err = 1;$('rand_code').focus();break;
            default:
                    err = 1;i = '未知错误('+stat+')，请稍候再试';
        }
    } catch(e) {
        alert(e);
        i = '服务器错误，请稍候再试';
        err = 1;
    }

    $('submit').disabled = false;
    if (i) {
        var t = (err==1 ? 'error' : 'notice');
        d.update('<div class="'+ t +'">' + i + '</div>');
        d.show();
        if (timer) window.clearTimeout(timer);
        timer = setTimeout( "$('updatemsg2').hide();", 20000);
    }
    if (ok) d.hide();
}
